import { _decorator,Component ,instantiate,Label,Node, Prefab, resources, Sprite, SpriteFrame } from 'cc';
import { Core } from '../Core/Core';
import { PicPath, PrefabPath } from '../Config/ResourceConfig';
import { ItemBox } from './ItemBox';
import { EPlayerType, EView } from '../Config/Enum';
import { ResourceManager } from '../Core/ResourceManager';
import { PassiveSkillsConfig } from '../Config/SkillConfig';
import { PlayerConfig } from '../Config/PlayerConfig';


const { ccclass, property } = _decorator;

@ccclass('ChooseBoard')
export class ChooseBoard extends Component {



    ndBG: Node = null!; // 背景节点
    ndBoard: Node = null!; // 选择框节点
    lbTitle: Label = null!; // 标题标签



    protected onLoad(): void {
        this.ndBG = this.node.getChildByName("BG");
        this.ndBoard = this.node.getChildByName("Board");

        this.lbTitle = this.node.getChildByName("Title").getComponent(Label);
        

        
    }

    protected onEnable(): void {
        this.ndBG.on(Node.EventType.TOUCH_END, this.onButtonCloseWindow, this);

        //this.node.on(Node.EventType.TOUCH_END, this.onBtnOpenChooseDetail, this);

        if(Core.Instance.currentView === EView.PlayerView){     
            this.loadPassiveSkillList();   
            
        }else if(this.node.parent.name === EView.MartialView){
            this.loadPlayerList();
        }


        
    }

    protected onDisable(): void {

        this.ndBG.off(Node.EventType.TOUCH_END, this.onButtonCloseWindow, this);
        //this.node.off(Node.EventType.TOUCH_END, this.onBtnOpenChooseDetail, this);
        
    }

    protected start(): void {
        
    }



    onButtonCloseWindow() {
        this.node.active = false;
    }

    onBtnOpenChooseDetail(){
        console.log("打开选择框详情");
        this.node.parent.parent.parent.getChildByName("ChooseBoard").active = true;


    }

    loadPlayerList(){
        this.lbTitle.string = "选择义士";

        console.log("加载玩家列表Core.Instance.unlockedPlayers:", Core.Instance.unlockedPlayers);

        // 获取已解锁的玩家
        const playerList = [...Core.Instance.unlockedPlayers];
        //把assignedPlayers里的玩家从playerList里去掉
        Object.keys(Core.Instance.assignedPlayers).forEach(assignedPlayer => {
            const index = playerList.indexOf(Core.Instance.assignedPlayers[assignedPlayer]);
            if (index > -1) {
                playerList.splice(index, 1);
            }
        });

        console.log("已解锁的玩家:", playerList);

        // 清空现有的选择框内容
        this.ndBoard.removeAllChildren();

        // 遍历玩家列表，创建选择项
        playerList.forEach(playerName => {
            resources.load(PrefabPath.ChooseBoardItem, Prefab, (err, prefab) => {
                const newNode = instantiate(prefab);
                this.ndBoard.addChild(newNode);
                newNode.name = playerName; // 设置节点名称为玩家名称
                const itemBoxComp = newNode.getComponent(ItemBox);
                if (itemBoxComp) {
                    itemBoxComp.type = EPlayerType
                    // 这里可以添加更多初始化代码，例如设置显示的玩家头像或名称
                }

                itemBoxComp.setDesc(PlayerConfig[playerName].name);
                itemBoxComp.setIcon(PlayerConfig[playerName].avatar);
                itemBoxComp.disableMask()


                //newNode.getChildByName("Mask").active = false;

                //newNode.getChildByName("Icon").getComponent(Sprite).spriteFrame = ResourceManager.Instance.getRes<SpriteFrame>(PicPath[playerName + "Avatar"]+"/avatar");
            //     ResourceManager.Instance.loadRes<SpriteFrame>(PicPath[playerName + "Avatar"]+"/avatar")
            //     .then((spriteFrame) => {
            //         newNode.getChildByName("Icon").getComponent(Sprite).spriteFrame = spriteFrame;
            //     })
            //     .catch((error) => {
            //         console.error("加载义士头像失败:", error);  
            // });


        })
        });

    }

    loadPassiveSkillList(){
        console.log("加载被动武学列表,Core.Instance.currentPlayer",Core.Instance.currentPlayer);
        this.lbTitle.string = "选择心法";

        let passiveSkills = Core.Instance.players.get(Core.Instance.currentPlayer).skillData.passiveSkills;

        console.log("被动武学列表:", passiveSkills);
        // 清空现有的选择框内容
        this.ndBoard.removeAllChildren();
        // 遍历被动武学列表，创建选择项
        passiveSkills.forEach(skillId => {
            resources.load(PrefabPath.ChooseBoardItem, Prefab, (err, prefab) => {
                const newNode = instantiate(prefab);
                this.ndBoard.addChild(newNode);
                newNode.name = skillId.toString(); // 设置节点名称为武学ID
                const itemBoxComp = newNode.getComponent(ItemBox);
                if (itemBoxComp) {
                    itemBoxComp.type = "PassiveSkill"
                    // 这里可以添加更多初始化代码，例如设置显示的武学图标或名称
                }

                itemBoxComp.setDesc(PassiveSkillsConfig[skillId].desc);
                itemBoxComp.setIcon(PassiveSkillsConfig[skillId].icon);
                itemBoxComp.setMask(PassiveSkillsConfig[skillId].levelLimit);


                //PassiveSkillsConfig[skillId].levelLimit是武学解锁等级，如果玩家等级小于这个值，遮罩显示
                // if(Core.Instance.players.get(Core.Instance.currentPlayer).level > PassiveSkillsConfig[skillId].levelLimit){
                //     newNode.getChildByName("Mask").active = false;
                // } else {
                //     newNode.getChildByName("Mask").active = true;
                // }



                //console.log(skillId+"Icon")
                if(Core.Instance.players.get(Core.Instance.currentPlayer).level >= 5){
                    //newNode.getChildByName("Icon").getComponent(Sprite).spriteFrame = ResourceManager.Instance.getRes<SpriteFrame>(PicPath[skillId+"Icon"]);
                    ResourceManager.Instance.loadRes<SpriteFrame>(PicPath[skillId+"Icon"])
                    .then((spriteFrame) => {
                        newNode.getChildByName("Icon").getComponent(Sprite).spriteFrame = spriteFrame;
                    })
                    .catch((error) => {
                        console.error("加载被动武学图标失败:", error);
                    });

                }

            });
        })
    }




}


